﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace BEELab
{
    public partial class EditProfile : System.Web.UI.Page
    {
        /// <summary>
        /// Occures on every page load (first time or Post Back).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && Session["UserID"] != null)
            {
                SqlCommand command = new SqlCommand();
                command.CommandText = "SELECT * FROM Users WHERE ID=@ID";
                command.Parameters.Add(new SqlParameter("@ID", int.Parse(Session["UserID"].ToString())));
                DataTable dt = BEELab.Data.DBHelper.ExecuteQuery(command);

                if (dt != null && dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    txtFirstName.Text = dr["FirstName"].ToString();
                    txtLastName.Text = dr["LastName"].ToString();
                    txtUniversity.Text = dr["University"].ToString();
                    txtEmail.Text = dr["Email"].ToString();
                    txtConfirmEmail.Text = dr["Email"].ToString();
                }
            }
        }

        /// <summary>
        /// Updates current user's profile on DB: ID, FirstName, LastName, Email, University
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Session["UserID"] != null)
            {
                BEELab.Logic.UserManagement.UpdateUser(int.Parse(Session["UserID"].ToString()), txtFirstName.Text, txtLastName.Text, txtEmail.Text, txtUniversity.Text);
            }
        }

        /// <summary>
        /// Occures once the user insert a text to E-Mail address text box in order to update it's details.
        /// Checks if user exists on DB. If not - an error will be presented on screen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtEmail_TextChanged(object sender, EventArgs e)
        {
            revtxtEmail.Visible = EmailRegistered(txtEmail.Text);
        }

        /// <summary>
        /// Gets an email address, checks if exists on DB
        /// </summary>
        /// <param name="Email">User's email address</param>
        /// <returns>True if user exists on DB, False otherwise</returns>
        private Boolean EmailRegistered(string email)
        {
            return BEELab.Logic.UserManagement.EmailRegistered(email);
        }
    }
}